package com.deepseek.controller;

import com.deepseek.model.dto.FileInfoDTO;
import com.deepseek.model.dto.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/file")
public class FileController {

    @PostMapping (value = "/upload",consumes = "multipart/form-data")
    public Result upload(
            @RequestParam("file")MultipartFile file,
            @RequestParam("userId")String userId
            ) {
        // 验证参数是否为空
        if (file.isEmpty()) {
            return Result.error().code(400).message("文件不能为空");
        }
        if (userId == null || userId.trim().isEmpty()) {
            return Result.error().code(400).message("用户ID不能为空");
        }

        try {
            // 生成UUID作为fileId
            String fileId = UUID.randomUUID().toString();
            String originalFilename = file.getOriginalFilename();
            // 生成文件路径
            String currentDate = LocalDate.now().toString();
            String newFileName = fileId + "_" + originalFilename;
            Path targetPath = Paths.get("uploads", currentDate, newFileName);
            Files.createDirectories(targetPath.getParent()); // 创建目录

            // 保存文件
            file.transferTo(targetPath);

            // 构建响应数据
            FileInfoDTO responseData = new FileInfoDTO();
            responseData.setFileId(fileId);
            responseData.setFileName(originalFilename);
            responseData.setFileType(file.getContentType());
            responseData.setFileSize(file.getSize());
            responseData.setFilePath(targetPath.toString());

            return Result.ok()
                    .data("fileId",responseData.getFileId())
                    .data("fileName",responseData.getFileName())
                    .data("fileType",responseData.getFileType())
                    .data("fileSize",responseData.getFileSize())
                    .data("filePath",targetPath.toString());
        } catch (IOException e) {
            log.error(e.getMessage());
            return Result.error().message("文件上传失败");
        }

    }
}
